package com.dl.test.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * @author DL
 * @create 2022-09-29 9:24
 */
@RestController
@RequestMapping("/axios")
public class AxiosController {

    @Resource
    private HttpServletRequest request;

    @Resource
    private HttpServletResponse response;

    @RequestMapping("/test")
    public void test(){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            System.out.println(cookieName + "=" + cookieValue);
        }
    }

    @RequestMapping("/addCookie")
    public void addCookie(){
        //addOneCookie(response, "username", "dl", "https://fanyi.baidu.com/");
        response.setHeader("Set-Cookie", "username=dl;path=/;");
    }

    /**
     * 往响应头添加一个Cookie，要传三个参数： Cookie键，Cookie值，Cookie所在域名
     */
    public static void addOneCookie(HttpServletResponse httpServletResponse, String cookieKey, String cookieValue, String cookieDomain) {
        // Cookie过期时间
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR, 6); // 6小时后过期
        Date date = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.CHINA);
        String responseHeaderString = cookieKey + "=" + cookieValue + ";";
        httpServletResponse.addHeader("Set-Cookie",responseHeaderString + "Path=/; Domain=" + cookieDomain + "; Expires=" + sdf.format(date) + "; SameSite=None; Secure"); // Chrome浏览器跨域写Cookie需要带的属性
    }
}
